<template>
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="脚本名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入脚本名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryParams.params"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增脚本</el-button>
      </el-col>
   
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="60" prop="number" />
      <el-table-column label="脚本名称" align="center" prop="name" />
      <el-table-column label="创建人" align="center" prop="creatorName" />
      <el-table-column label="创建时间" align="center" prop="createTime" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
           <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看脚本</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleExecute(scope.row)"
          >执行脚本</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="脚本名称" prop="name" >
          <el-input v-model="form.name" placeholder="请输入脚本名称" />
        </el-form-item>
        <el-form-item label="脚本内容" >
          <Shditor
            ref="editors"
            :content="value"
            :readOnly="readOnly"
            @change="editorChange"></Shditor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="lookOpen" width="700px" append-to-body>
          <Shditor
            ref="editors"
            :content="value"
            :readOnly="readOnly"
            @change="editorChange"></Shditor>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="hostOpen" width="700px" append-to-body>
      <el-form :model="queryHostParams" ref="queryHostForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主机名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入主机名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="主机地址" prop="hostname">
        <el-input
          v-model="queryParams.hostname"
          placeholder="请输入主机地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="hostList" @selection-change="handleSelectionHostChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主机名称" align="center" prop="name" />
      <el-table-column label="主机地址" align="center" prop="hostname" />
      <el-table-column label="创建时间" align="center" prop="createTime" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="hostTotal>0"
      :total="hostTotal"
      :page.sync="queryHostParams.pageNum"
      :limit.sync="queryHostParams.pageSize"
      @pagination="getHostList"
    />
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitHostExecute">确 定</el-button>
        <el-button @click="hostCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, detail, del, add, put,run  } from "@/api/script/script";
import { list as hostList } from "@/api/script/host";
import Shditor from '@/components/common/ace'
export default {
  name: "Script",
  components:{Shditor},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      hostIds:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      hostTotal: 0,
      // 表格数据
      postList: [],

      //主机表格数据
      hostList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      hostOpen: false,
      //查看脚本
      isLook: true,
      //是否可以编辑脚本
      readOnly: false,
      //是否打开选择主机
      isSelect: false,
      lookOpen: false,
      scriptId: 0,
      value:'echo "hello shell"',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        params: [],
        name: undefined,
        
      },
      queryHostParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        hostname: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "脚本名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    handleExecute(row) {
      this.isSelect = true;
      this.hostOpen=true
      this.hostIds = [];
      this.title = '添加执行主机'
      this.scriptId = row.id
      this.getHostList()
    },
    //监听编辑器的变化
    editorChange(val){
      this.value =  val;
    },
    //查看脚本
    handleView(row) {
      this.lookOpen=true
      // this.isLook = false
      this.readOnly = true
      this.value = row.content
      this.title = '查看脚本'
   
    },
    getHostList() {
      this.loading = true;
      hostList(this.queryHostParams).then(response => {
        this.hostList = (response.rows||[]).map((item,index) => {item.number=index+1 ;return item});
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.queryParams.startTime = this.queryParams.params[0]
      this.queryParams.endTime = this.queryParams.params[1]
      list(this.queryParams).then(response => {
        this.postList = (response.rows||[]).map((item,index) => {item.number=index+1 ;return item});
        this.hostTotal = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 取消按钮
    hostCancel() {
      this.hostOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        content: undefined,
     
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.params=[]
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id).join(',')
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    handleSelectionHostChange(selection) {
      this.hostIds = selection.map(item => item.id)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加脚本";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isLook=true
      let ids = row.id || this.ids
      detail(ids).then(response => {
        this.form.name = response.data.name;
        this.form.id = response.data.id;
        this.value = response.data.content;
        this.open = true;
        this.title = "修改脚本";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.content = this.value
          if (this.form.id != undefined) {
            put(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitHostExecute: function() {
      if(this.hostIds&&this.hostIds.length >0){
        this.loading = true;
        run({scriptId:this.scriptId,hostIds:this.hostIds.join(',')})
        .then(res => {
            this.$modal.msgSuccess("执行成功");
            this.hostOpen = false;
            this.loading = false;
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + id + '"的数据项？').then(function() {
        return del(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.editor-tc {
  height: 400px;
  width: 120px;
}
</style>
